import axios from "axios";
// import { ElMessage, ElMessageBox, ElNotification } from "element-plus";
import router from "@/router";
import { getToken } from "@/utils/auth";
import cache from "@/plugins/cache";
import { tansParams } from "@/utils/zpPlatform";
import errorCode from "@/utils/errorCode";
import "element-plus/theme-chalk/el-message.css";
import "element-plus/theme-chalk/el-message-box.css";
import { useUserStoreHook } from "@/store/modules/user";

const cns = getCurrentInstance();
// 是否显示重新登录
export const isRelogin = { show: false };

const service = axios.create({
  // axios中请求配置有baseURL选项，表示请求URL公共部分
  //@ts-ignore
  baseURL: import.meta.env.VITE_APP_TARGET_URL,
  timeout: 1000 * 12,
  withCredentials: false,
});
service.interceptors.request.use(
  (config) => {
    const useUserStore = useUserStoreHook();
    // 是否需要设置 token
    // const isToken = (config.headers || {}).isToken === false
    // 是否需要防止数据重复提交
    // const isRepeatSubmit = (config.headers || {}).repeatSubmit === false
    // if (getToken() && !isToken) {
    if (getToken()) {
      config.headers.Authorization = "Bearer " + getToken(); // 让每个请求携带自定义token 请根据实际情况自行修改
    }
    // get请求映射params参数
    if (config.method === "get" && config.params) {
      let url = config.url + "?" + tansParams(config.params);
      url = url.slice(0, -1);
      config.params = {};
      config.url = url;
    }
    if (config.method === "post" || config.method === "put") {
      const requestObj = {
        url: config.url,
        data:
          typeof config.data === "object"
            ? JSON.stringify(config.data)
            : config.data,
        time: new Date().getTime(),
      };
      const sessionObj = cache.session.getJSON("sessionObj");
      if (sessionObj === undefined || sessionObj === null) {
        cache.session.setJSON("sessionObj", requestObj);
      } else {
        const s_url = sessionObj["url"]; // 请求地址
        const s_data = sessionObj["data"]; // 请求数据
        const s_time = sessionObj["time"]; // 请求时间
        const interval = 1000; // 间隔时间(ms)，小于此时间视为重复提交
        if (
          s_data === requestObj.data &&
          requestObj.time - s_time < interval &&
          s_url === requestObj.url
        ) {
          const message = "数据正在处理，请勿重复提交";
          console.warn(`[${s_url}]: ` + message);
          return Promise.reject(new Error(message));
        } else {
          cache.session.setJSON("sessionObj", requestObj);
        }
      }
    }
    return config;
  },
  (error) => {
    Promise.reject(error);
  }
);
service.interceptors.response.use(
  (res) => {
    const useUserStore = useUserStoreHook();
    const data = res.data;
    // SecretDataFn(data)
    // 未设置状态码则默认成功状态
    const code = data.code || 200;
    // 获取错误信息
    const msg = errorCode[code] || data.msg || errorCode.default;
    // 二进制数据则直接返回
    if (
      res.headers["content-type"] === "application/octet-stream" ||
      res.request.responseType === "blob" ||
      res.request.responseType === "arraybuffer"
    ) {
      console.log(res);
      return res;
    }
    if (
      res.request.responseURL.indexOf("getNucleicAcid") >= 0 ||
      res.request.responseURL.indexOf("getHealthInfoLevel") >= 0
    ) {
      return data;
    }
    if (code === 401) {
      if (!isRelogin.show) {
        isRelogin.show = true;
        ElMessageBox.confirm(
          "登录状态已过期，您可以继续留在该页面，或者重新登录",
          "系统提示",
          {
            confirmButtonText: "重新登录",
            cancelButtonText: "取消",
            type: "warning",
          }
        )
          .then(() => {
            isRelogin.show = false;
            useUserStore.LogOut().then(() => {
              location.href = 8080 + "#/login";
            });
          })
          .catch(() => {
            isRelogin.show = false;
          });
      }
      // eslint-disable-next-line prefer-promise-reject-errors
      return Promise.reject("无效的会话，或者会话已过期，请重新登录。");
    } else if (code === 500) {
      ElMessage({
        message: msg,
        type: "error",
      });
      return Promise.reject(new Error(msg));
    } else if (code !== 200) {
      ElNotification.error({
        title: msg,
      });
      // eslint-disable-next-line prefer-promise-reject-errors
      return Promise.reject("error");
    } else {
      return data;
    }
  },
  (error) => {
    let { message } = error;
    if (message === "Network Error") {
      message = "后端接口连接异常";
    } else if (message.includes("timeout")) {
      message = "系统接口请求超时";
    } else if (message.includes("Request failed with status code")) {
      message = "系统接口" + message.substr(message.length - 3) + "异常";
    }
    ElMessage({
      message: message,
      type: "error",
      duration: 5 * 1000,
    });
    return Promise.reject(error);
  }
);

/**
 * http握手错误
 * @param result 响应回调,根据不同响应进行不同操作
 */
// function errorHandle(result: any) {
//   switch (result.code) {
//     case 50011:
//       setTimeout(() => {
//         store.dispatch("setOutin", {});
//         router.push({
//           path: "/login",
//           query: {
//             T: new Date().getTime(),
//           },
//         });
//       }, 1500);
//       ElNotification({
//         title: "提示",
//         message: result.msg,
//         type: "warning",
//       });
//       break;
//     case 50010:
//       setTimeout(() => {
//         store.dispatch("setOutin", {});
//         router.push({
//           path: "/login",
//           query: {
//             T: new Date().getTime(),
//           },
//         });
//       }, 1500);
//       ElNotification({
//         title: "提示",
//         message: result.msg,
//         type: "warning",
//       });
//       break;
//     case 50012:
//       setTimeout(() => {
//         store.dispatch("setOutin", {});
//         router.push({
//           path: "/login",
//           query: {
//             T: new Date().getTime(),
//           },
//         });
//       }, 1500);
//       ElNotification({
//         title: "提示",
//         message: result.msg,
//         type: "warning",
//       });
//       break;
//     case 403:
//       break;
//     default:
//       ElNotification({
//         title: "提示",
//         message: "异常错误！",
//         type: "warning",
//       });
//   }
// }

/**
 * get请求
 * @param params 参数
 * @param jwt  是否token校验
 * @param url  接口
 */
export const getData = (url: string, params: any, isJwt: boolean) => {
  const headers = { isJwt: isJwt };
  return new Promise((resolve, reject) => {
    service
      .get(url, {
        headers: headers,
        params: params,
      })
      .then((response: any) => {
        resolve(response);
      })
      .catch((error: any) => {
        reject(error.msg);
      });
  });
};

/**
 * post请求
 * @param params 参数
 * @param jwt  是否token校验
 * @param url   接口
 */
export const postData = (url: string, params: any, isJwt: boolean) => {
  const headers = { isJwt: isJwt };
  return new Promise((resolve, reject) => {
    service
      .post(url, params, {
        headers: headers,
      })
      .then((response: any) => {
        resolve(response);
      })
      .catch((error: any) => {
        reject(error.msg);
      });
  });
};
export default service;
